<?php
/**
 * Created by PhpStorm.
 * User: caoyangmin
 * Date: 16/11/13
 * Time: 下午10:58
 */

namespace Once\Annotations\Controller;
use Once\Annotations\BaseAnnotationHandler;
use Once\Container\ControllerContainer;
use Once\Utils\TypeHint;

class AnnReturn extends BaseAnnotationHandler
{
    public function __construct(ControllerContainer $container){
        $this->container = $container;
    }

    /**
     * @param $target
     * @param $name
     * @param $value
     * @return bool
     */
    protected function handleMethod($target, $name, $value)
    {
        $route = $this->container
            ->getRoute($target);

        if(!$route){
            return false;
        }

        $params = $this->getParams($value, 2);
        $type = $doc = null;
        if(count($params)>0){
            try{
                $type = TypeHint::normalize($params[0], $this->container->getClassName());
            }catch (\Exception $e){
                \Once\Utils\Logger::warning("{$this->container->getClassName()}::$target @$name $value. decide return type failed with $e->getMessage()");
            }

        }
        if(count($params)>1){
            $doc = $params[1];
        }

        $meta = $route->getActionInvoker()
            ->getReturnHandler()
            ->getMapping('$.response.content');
        if($meta){
            $meta->doc = $doc;
            $meta->type = $type;
        }

        return true;
    }

    /**
     * @var ControllerContainer
     */
    private $container;
}